﻿using BlazorComponent;
using ImoviesBlazor.Shared.Dtos;
using ImoviesBlazor.Shared.Utils;
using System.Net.Http.Json;
using System.Text.Json;

namespace ImoviesBlazor.Client.Pages.admin
{
    public partial class ARManage
    {


        /// <summary>
        /// 表格展示用类
        /// </summary>
        public class TableViewModel
        {
            public uint Id { get; set; }
            public uint Year { get; set; }
            public string Comment { get; set; }

            public TableViewModel() { }

        }

        /// <summary>
        /// 视频类型选择类
        /// </summary>
        public class SelectItem
        {
            public string Label { get; set; }
            public string Value { get; set; }

            public SelectItem(string label, string value)
            {
                this.Label = label;
                this.Value = value;
            }
        }

        /// <summary>
        /// 表头定义
        /// </summary>
        public List<DataTableHeader<TableViewModel>> headers = new List<DataTableHeader<TableViewModel>>
        {
            new (){ Text= "Id", Value= nameof(TableViewModel.Id),Sortable=false,Width="80px",Align="center"},
            new (){ Text= "年份", Value= nameof(TableViewModel.Year),Width="200px",Align="center"},
            new (){ Text= "点评", Value= nameof(TableViewModel.Comment),Sortable=false, Align="center"},
            new (){ Text= "操作", Value= "actions",Sortable=false,Width="100px",Align="center" }
        };

        /// <summary>
        /// 显示到表格的年评数据
        /// </summary>
        public List<TableViewModel> annualReviewList = new List<TableViewModel>();

        /// <summary>
        /// 被选中的视频分类
        /// </summary>
        public string selectedVideoCate = null;

        public bool _dialogEdit;
        public bool _dialogAdd;
        public bool _dialogDelete;

        List<SelectItem> selectItems = new()
        {
            new SelectItem("电视剧", "电视剧"),
            new SelectItem("电影", "电影"),
            new SelectItem("动漫", "动漫")
        };


        public TableViewModel _editedItem = new TableViewModel();
        public TableViewModel _addItem = new TableViewModel();

        /// <summary>
        /// 关闭对话框
        /// </summary>
        public void Close()
        {
            _dialogEdit = false;
            _dialogAdd = false;
            _editedItem = new TableViewModel();
            _addItem = new TableViewModel();
        }

        /// <summary>
        /// 显示添加表单
        /// </summary>
        public void ShowAddForm()
        {
            if (string.IsNullOrEmpty(selectedVideoCate))
            {
                return;
            }
            _dialogAdd = true;
        }

        /// <summary>
        /// 提交编辑
        /// </summary>
        public async Task SubmitEdit()
        {
            AnnualReviewForUpdateDto data = new AnnualReviewForUpdateDto
            {
                Id = _editedItem.Id,
                Year = _editedItem.Year,
                Comment = _editedItem.Comment,
            };
            var res = await HttpClient.PutAsJsonAsync<AnnualReviewForUpdateDto>("/api/AnnualReview", data);
            if (!res.IsSuccessStatusCode)
            {
                await PopupService.ToastAsync((config) =>
                {
                    config.Title = "操作失败";
                    config.Duration = 1;
                    config.Type = BlazorComponent.AlertTypes.Error;
                });
                return;
            }
            _dialogEdit = false;
            _editedItem = new TableViewModel();
        }

        /// <summary>
        /// 提交添加
        /// </summary>
        public async Task SubmitAddAsync()
        {
            AnnualReviewsVideoCate vcate;
            switch (selectedVideoCate)
            {
                case "电视剧":
                    vcate = AnnualReviewsVideoCate.Teleplay;
                    break;
                case "电影":
                    vcate = AnnualReviewsVideoCate.Movie;
                    break;
                case "动漫":
                    vcate = AnnualReviewsVideoCate.Animation;
                    break;
                default:
                    vcate = AnnualReviewsVideoCate.Teleplay;
                    break;
            }
            AnnualReviewForCreateDto data = new AnnualReviewForCreateDto
            {
                VideoCate = vcate,
                Year = _editedItem.Year,
                Comment = _editedItem.Comment,
            };
            var res = await HttpClient.PostAsJsonAsync<AnnualReviewForCreateDto>("/api/AnnualReview", data);
            if (!res.IsSuccessStatusCode)
            {
                await PopupService.ToastAsync((config) =>
                {
                    config.Title = "操作失败";
                    config.Duration = 1;
                    config.Type = BlazorComponent.AlertTypes.Error;
                });
                return;
            }
            _dialogAdd = false;
            _addItem = new TableViewModel();
        }

        /// <summary>
        /// 编辑按钮点击
        /// </summary>
        /// <param name="item"></param>
        public void EditItem(TableViewModel item)
        {
            _editedItem = item;
            _dialogEdit = true;
        }

        /// <summary>
        /// 待删除的记录id
        /// </summary>
        private uint awaitDelId;
        /// <summary>
        /// 删除按钮点击
        /// </summary>
        /// <param name="item"></param>
        public void DeleteItem(uint itemId)
        {
            awaitDelId = itemId;
            _dialogDelete = true;
        }

        /// <summary>
        /// 提交删除
        /// </summary>
        public async Task DeleteItemConfirmAsync()
        {
            if (awaitDelId <= 0)
            {
                return;
            }

            var res = await HttpClient.DeleteAsync($"/api/AnnualReview/{awaitDelId}");
            if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
            {
                _dialogDelete = false;
                return;
            }
            await PopupService.ToastAsync((config) =>
            {
                config.Title = "操作失败";
                config.Duration = 1;
                config.Type = BlazorComponent.AlertTypes.Error;
            });

            CloseDelete();
        }

        /// <summary>
        /// 关闭删除对话框
        /// </summary>
        public void CloseDelete()
        {
            _dialogDelete = false;
            awaitDelId = 0;
            _editedItem = new TableViewModel();
        }


        /// <summary>
        /// 视频类型选择改变
        /// </summary>
        /// <returns></returns>
        public async Task VcateSelectedChange(string value)
        {
            selectedVideoCate = value;
            switch (value)
            {
                case "电视剧":
                    annualReviewList = await GetAnnualReviews(AnnualReviewsVideoCate.Teleplay);
                    break;
                case "电影":
                    annualReviewList = await GetAnnualReviews(AnnualReviewsVideoCate.Movie);
                    break;
                case "动漫":
                    annualReviewList = await GetAnnualReviews(AnnualReviewsVideoCate.Animation);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 视频类型选择下拉框清空事件
        /// </summary>
        public void ClearVcate()
        {
            selectedVideoCate = null;
            annualReviewList = new List<TableViewModel>();
        }


        /// <summary>
        /// 根据视频分类获取年评数据
        /// </summary>
        /// <param name="vcate"></param>
        /// <returns></returns>
        private async Task<List<TableViewModel>> GetAnnualReviews(AnnualReviewsVideoCate vcate)
        {
            var resp = await HttpClient.GetAsync($"api/AnnualReview/{(uint)vcate}");
            var resData = JsonSerializer.Deserialize<List<TableViewModel>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });

            return resData ?? new List<TableViewModel>();
        }
    }
}
